/**
 * 功能描述
 */

define(function (require, exports, module) {
	var Form = require("form");
	var aw = require("ajaxwrapper");
	var Dialog=require("dialog");
	
    module.exports = {
    	save:function(widget){
    		var form=widget.get("profile");
    		var tab = widget.get("tab");
    		tab.setActive(1);
    		if(form.valid()){
    			tab.setActive(0);
    			var pkQuestionAnswerSheet = form.getValue("pkQuestionAnswerSheet");
    			var data = {
    					pkQuestionAnswerSheet : pkQuestionAnswerSheet,
    					questionnaire : form.getValue("pkQuestionaire"),
    					//questionAnswerSheetView : {
    						list : []
    					//}
    			};
    			
    			var items = form.get("model").items;
    			for(var i in items){
    				var children = items[i].children || [];
    				for(var j in children){
    					var name = children[j].name;
    					
    					if(name.indexOf("question_") != -1){
    						
    						var optionCell = form.getValue(name);
    						
    						if(optionCell && typeof optionCell === "object" && optionCell.constructor === Array){
    							//多选框
    							for(var k in optionCell){
    								//data.questionAnswerSheetView.list.push({
    								data.list.push({
    									optionCell : optionCell[k],
    									pkQuestionAnswer : pkQuestionAnswerSheet !== undefined ? form.getValue("questionAnswer_"+name.split("_")[1])/*修改*/ : undefined/*新增*/,
    									other : $(".J-other-answer-"+optionCell[k]).val()
    								});
    							}
    						}else{
    							//单选框
    							data.list.push({
    								optionCell : optionCell,
    								pkQuestionAnswer : pkQuestionAnswerSheet !== undefined ? form.getValue("questionAnswer_"+name.split("_")[1])/*修改*/ : undefined/*新增*/,
    								other : $(".J-other-answer-"+optionCell).val()
    							});
    						}
    					}
    				}
    			}
    			
    			return data;
    		}else{
    			return [];
    		}
    	},
		/**
		 * 获取表单字段
		 * lixiaochen
		 */
		initForm : function(widget,data){
			var profile = new Form({
				parentNode : "#questionnaire",
				model : {
					id : "pkQuestionaire",
					type : "profile",
					defaultButton : false,
					items : this.getQuestionaireForm(widget,data)
				}
			});
			widget.set("profile",profile);
		},
		/**
         * 获取表单字段
		 * lixiaochen
         */
        getQuestionaireForm : function(widget,data){
        	var formItems = [];
			
			if(data && data.length != 0){
				var ret = data[0];
				//获取区域
				var questionAreas = ret.questionAreas || [];
				for(var i in questionAreas){
					var formItem = {
						title : questionAreas[i].name,
						children : []
					};
					
					formItems.push(formItem);
					
					var questionQuotes = questionAreas[i].questionQuotes || [];
					for(var i in questionQuotes){
						var question = questionQuotes[i].question;
						
						var childrenItem = {
							name : "question_" + question.pkQuestion,
							label : question.name,
							type : question.type.key == "Single" ? "radio" : "checkbox",
							list : [],
							validate : ["required"]
						};
						formItem.children.push(childrenItem);
						formItem.children.push({
							name : "questionAnswer_"+question.pkQuestion,
							type : "hidden"
						});
						
						for(var j in question.optionCells){
							var content = question.optionCells[j].context;
							if(content.indexOf("()") != -1){
								content = content.replace(/\(\)/g,"") + "<input type='text' class='other-answer J-other-answer form-control J-other-answer-"+question.optionCells[j].pkOptionCell+"' placeholder='请输入想要的答案'/>";
							}
							childrenItem.list.push({
								key : question.optionCells[j].pkOptionCell,
								value :  content
							});
						}
					}
				}
			}
			
			//增加答卷主键隐藏字段
			formItems[0].children.push({
				name : "pkQuestionAnswerSheet",
				type : "hidden"
			});
			
			//增加问卷主键隐藏字段
			formItems[0].children.push({
				name : "pkQuestionaire",
				type : "hidden",
				defaultValue : widget.get("pkQuestionnaire")
			});
			
			//增加问卷主键隐藏字段
			formItems[0].children.push({
				name : "version",
				type : "hidden",
				defaultValue : 0
			});
			
			return formItems;
        },
        queryQuestionnaire : function(type,widget){
        	var that=this;
        	//1.查询问卷
        	aw.ajax({
				url:"api/questionnaire/query",
				//由于页面需要 所以该为同步请求 慎用！
				async: false,
				data : {
					"status" : "Setting",
					fetchProperties : "pkQuestionnaire," +
							"name," +
							"questionAreas.pkQuestionArea," +
							"questionAreas.name," +
							"questionAreas.questionQuotes.pkQuestionQuotes," +
							"questionAreas.questionQuotes.cond," +
							"questionAreas.questionQuotes.orderCode," +
							"questionAreas.questionQuotes.gridShow," +
							"questionAreas.questionQuotes.question.pkQuestion," +
							"questionAreas.questionQuotes.question.name," +
							"questionAreas.questionQuotes.question.type," +
							"questionAreas.questionQuotes.question.version," +
							"questionAreas.questionQuotes.question.optionCells.pkOptionCell," +
							"questionAreas.questionQuotes.question.optionCells.sequence," +
							"questionAreas.questionQuotes.question.optionCells.version," +
							"questionAreas.questionQuotes.question.optionCells.score," +
							"questionAreas.questionQuotes.question.optionCells.context,"
				},
				dataType:"json",
				success:function(data){
					if (data.length == 0) {
						loadCustomerTrace = false;
						Dialog.alert({
							content:"请先启用一个访问卷",
							confirm:function(){
								widget.openView({
									url : "eling/elcms/callcenter/callcenter"
								})
							}
						})
					}else{
						//0.缓存问卷主键
						widget.set("pkQuestionnaire",data[0].pkQuestionnaire);
						
						//3.组织数据获得问卷表单
						that.initForm(widget,data);
						
					}
				}
        	});
        },
        /**
		 * 为问卷赋值
		 * lixiaochen
		 */
		setQuestionaire : function(data,widget){
			
			if(data){
				var form = widget.get("profile");
				form.reset();
//				widget.get("tab").setActive(1);
				//1.设置答卷主键，问卷主键，答卷版本号
				if(!widget.get("edit")){
					form.setData({
						pkQuestionAnswerSheet : data.pkQuestionAnswerSheet,
						version : data.version,
						questionnaire :	widget.get("pkQuestionnaire")			
					});
				}else{
					form.setData({
						version : 0,
					});
				}
				
				//2.设置每道题的答案，由于每道题的name实际上是question_问题的pk，而答案集合可能是一道题的多个答案，所以先需要将所有答案按照题分组。
				var anwsers = data.questionAnswers || [];
				var questionMap = {}/*pkQuestion<->[pkOptionCell]*/ ,questionOtherContentMap = {}/*pkQuestion<->other*/, questionAnswerMap = {}/*pkQuestion<->pkQuestionAnswer*/;
				for(var i in anwsers){
					var pkQuestion = anwsers[i].optionCell.question.pkQuestion;
					if(!questionMap[pkQuestion]){
						questionMap[pkQuestion] = [];
					}
					if(!questionAnswerMap[pkQuestion]){
						questionAnswerMap[pkQuestion] = anwsers[i].pkQuestionAnswer;
					}
					questionMap[pkQuestion].push(anwsers[i].optionCell.pkOptionCell);
					questionOtherContentMap[anwsers[i].optionCell.pkOptionCell] = anwsers[i].other;
				}
				//设置单选框
				for(var j in questionMap){
					if($("input[name=question_"+j+"]").length>0){
						form.setValue("question_"+j,questionMap[j]);
					}
				}
				//设置每道题的"其它"答案
				for(var k in questionOtherContentMap){
					widget.$(".J-other-answer-"+k).val(questionOtherContentMap[k]);
				}
				//设置每个已选答案的pk
				for(var n in questionAnswerMap){
					if($("input[questionAnswer_"+n+"]").length>0){
						form.setValue("questionAnswer_"+n,questionAnswerMap[n]);
					}
				}
			}
		},
    };
});
